package com.xm.runtimetask;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;

import com.xm.runtimetask.util.AppUtils;
import com.xm.runtimetask.util.CmdUtil;
import com.xm.runtimetask.util.TimeTaskUtil;
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.Random;

/**
 * 自动滑屏Service
 */
public class AutoSwipService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null || intent.getAction() == null
                || intent.getAction().equals("")||
                intent.getAction().equals(TimeTaskUtil.TIMETASK_RUN_ACTION)){//执行任务
            if (TimeTaskUtil.getInstance(getApplication()).isTimeTaskRuning()){
                Log.e("test","==AutoSwipService=runTimeTask====");
                runTimeTask();
            }
        }else if (intent.getAction().equals(TimeTaskUtil.TIMETASK_STOP_ACTION)){//停止任务
            Log.e("test","==AutoSwipService=stopTimeTask====");
            stopTimeTask();
            TimeTaskUtil.getInstance(getApplication()).startCheckLockScreenAlarm();
        }else if (intent.getAction().equals(TimeTaskUtil.TIMETASK_START_EVERYDAY_ACTION)){//每天自动运行
            Log.e("test","==AutoSwipService=startEveryDay====");
            TimeTaskUtil.getInstance(getApplication()).cancelCheckLockScreenAlarm();
            unLockDeviceAndStartTimeTask();
        }else if (intent.getAction().equals(TimeTaskUtil.TIMETASK_UNRUN_CHECK_LOCK_SCREEN_ACTION)){//检查是否锁屏
            checkLockScreen();
        }
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    //=======================工作逻辑================================//

    /**
     * 执行任务
     */
    private void runTimeTask(){
        Random ra =new Random();
        final int time = ra.nextInt(18)+2;

        //熄屏或者锁屏就点亮解锁
        if (!AppUtils.isScreenOn(getApplication()) || AppUtils.isLockDevice(getApplication())){
            CmdUtil.execUnClockDeviceCmd(getApplication(), new CmdUtil.CmdListener() {
                @Override
                public void onResult(String result) {

                    if (AppUtils.isForeground(getApplicationContext()
                            ,AppUtils.skjHomeActivityClassName)){//当前页面是否是刷视频界面
                        Log.e("test","====快手极速版运行中==");
                        swipeScreen(time);
                        TimeTaskUtil.getInstance(getApplication()).runTimeTask(time);//执行定时循环
                    }else {//当前页面不是刷视频界面，重新启动app
                        AppUtils.resStartAPP(getApplicationContext(),AppUtils.skjPackName);
                        TimeTaskUtil.getInstance(getApplication()).runTimeTask(22);//执行定时循环
                    }
                }
            });
        }else{

            if (AppUtils.isForeground(getApplicationContext()
                    ,AppUtils.skjHomeActivityClassName)){//当前页面是否是刷视频界面
                Log.e("test","====快手极速版运行中==");
                swipeScreen(time);
                TimeTaskUtil.getInstance(getApplication()).runTimeTask(time);//执行定时循环
            }else {//当前页面不是刷视频界面，重新启动app
                AppUtils.resStartAPP(getApplicationContext(),AppUtils.skjPackName);
                TimeTaskUtil.getInstance(getApplication()).runTimeTask(22);//执行定时循环
            }
        }


    }

    /**
     * 停止任务
     */
    private void stopTimeTask(){
        TimeTaskUtil.getInstance(getApplication()).stopRunTimeTask();
        CmdUtil.execLockScreenCmd();//锁屏
    }

    /**
     * 执行滑屏操作
     * @param time
     */
    private void swipeScreen(final int time){
        int x1 = getRandomX();
        int x2 = x1;
        int y[] = getRandomY(time);
        CmdUtil.execSwipeScreenCmd(x1,y[0],x2,y[1]);
    }
    private int getRandomX(){
        Random ra =new Random();
        //保持在屏幕中间，左右各1/3的区域边界保留
        int result = ra.nextInt(AppUtils.getScreenWith()/3)+AppUtils.getScreenWith()/3;
        return result;
    }

    private int[] getRandomY(int time){
        int result[] = {0,0};
        int y1 = 0;
        int y2 = 0;
        Random ra =new Random();
        int spaceY = 10;
        if (time > 18){
            y1 = AppUtils.getScreenHeight()/4 + ra.nextInt(spaceY);//上一页
            y2 = AppUtils.getScreenHeight()*2/3 - ra.nextInt(spaceY);
        }else{
            y1 = AppUtils.getScreenHeight()*2/3 - ra.nextInt(spaceY);//下一页
            y2 = AppUtils.getScreenHeight()/4 + ra.nextInt(spaceY);
        }
        result[0] = y1;
        result[1] = y2;
        return result;
    }

    /**
     * 解锁设备开始定时任务
     */
    private void unLockDeviceAndStartTimeTask(){
         CmdUtil.execUnClockDeviceCmd(getApplication(), new CmdUtil.CmdListener() {
             @Override
             public void onResult(String result) {
                 if (!TimeTaskUtil.getInstance(getApplication()).isTimeTaskRuning()){//没有启动
                     int runTotalSecodes = 60*60*8;//8小时，
                     TimeTaskUtil.getInstance(getApplication()).startTimeTask(runTotalSecodes);
                 }
             }
         });
    }

    /**
     * 检查锁屏，未熄屏就熄灭屏幕
     */
    private void checkLockScreen(){
        if (!TimeTaskUtil.getInstance(getApplication()).isTimeTaskRuning()) {//没有任务在运行
            if (AppUtils.isScreenOn(getApplication())){//屏幕亮着
                CmdUtil.execLockScreenCmd();//熄屏
            }
        }
    }
}
